package com.david.musicapp.utils

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Build
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationCompat.PRIORITY_MAX
import com.david.core.event.MyEventBus
import com.david.core.event.Subscribe
import com.david.core.event.ThreadMode
import com.david.core.utils.ImageUtils
import com.david.musicapp.MusicApplication
import com.david.musicapp.PlayService
import com.david.musicapp.PlayService.SONG_ACTION_TYPE_RESTART
import com.david.musicapp.R
import com.david.musicapp.activity.SongActivity
import com.david.musicapp.bean.Song
import com.david.musicapp.event.SongStartEvent
import java.util.*


/**
 * 如果想加载网络列表在此处切换数据源
 */
class SongHelper {
    var isPlaying = false

    companion object {
        private lateinit var instance: SongHelper
        fun getInstance(): SongHelper {
            if (!this::instance.isInitialized) {
                instance = SongHelper()
                instance.init()
            }
            return instance
        }
    }

    @Volatile
    var currentType = 0//0:本地，1：云端，2：喜欢

    @Volatile
    var currentList = LocalMusicUtils.list

    @Volatile
    var cloudSongs = ArrayList<Song>()//云端歌曲列表

    fun init() {
        MyEventBus.getDefault().register(this, "onMusicPlayChange", SongStartEvent::class.java)
    }

    fun getSongFromId(id: Long): Song? {
        if (currentList == null) {
            return null
        }
        for (item in currentList) {
            if (item.id == id) {
                return item
            }
        }
        return null
    }

    fun getList(): List<Song> {
        return currentList
    }

    fun refreshList() {
        LocalMusicUtils.getMusic()
    }

    fun getChars(): Array<Char> {
        val array = ArrayList<Char>()
        for (item in currentList) {
            if (!array.contains(item.sortChar))
                array.add(item.sortChar)
        }
        return array.toTypedArray()
    }

    fun getNext(id: Long): Song? {
        for (index in 0 until currentList.size) {
            if (currentList[index].id == id) {
                return if (index == (currentList.size - 1)) {
                    currentList[0]
                } else
                    currentList[index + 1]
            }
        }
        return null
    }

    fun getPrevious(id: Long): Song? {
        for (index in 0 until currentList.size) {
            if (currentList[index].id == id) {
                return if (index == 0) {
                    currentList[currentList.size - 1]
                } else
                    currentList[index - 1]
            }
        }
        return null
    }

    var currentId: Long = -1

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onMusicPlayChange(event: SongStartEvent) {
        currentId = event.songId
    }

    private fun createNotificationChannel(channelId: String, channelName: String): String {
        val chan = NotificationChannel(
            channelId,
            channelName, NotificationManager.IMPORTANCE_HIGH
        )
        chan.lightColor = Color.BLUE
        chan.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
        val service = MusicApplication.instance()
            .getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        service.createNotificationChannel(chan)
        return channelId
    }

    var onTimeProgressListeners: ArrayList<PlayService.OnTimeProgressListener> = ArrayList()

    fun addTimeProgressListener(timeProgressListener: PlayService.OnTimeProgressListener) {
        onTimeProgressListeners.add(timeProgressListener)
    }

    fun removeTimeProgressListener(timeProgressListener: PlayService.OnTimeProgressListener) {
        onTimeProgressListeners.remove(timeProgressListener)
    }


    fun loadingCover(path: String?): Bitmap? {
        return LocalMusicUtils.loadingCover(path)
    }

    fun playMusic(songId: Long) {
        playMusic(MusicApplication.instance(), songId)
    }

    fun playMusic(context: Context, songId: Long) {
        if (songId < 0) {
            return
        }

        val intent = Intent(context, PlayService::class.java)
        //intent.putExtra(PlayService.SONG_ACTION_TYPE_KEY, SONG_ACTION_TYPE_RESTART)
        //context.startForegroundService(intent)
        //val intent = Intent(context, PlayService::class.java)
        intent.putExtra(PlayService.SONG_KEY, songId)
        context.startForegroundService(intent)

        isPlaying = true

    }

    fun pauseOrPlay(action: Int) {
        pauseOrPlay(MusicApplication.instance(), action)
    }

    fun pauseOrPlay(context: Context, action: Int): Boolean {
        val intent = Intent(context, PlayService::class.java)
        intent.putExtra(PlayService.SONG_ACTION_TYPE_KEY, action)
        context.startForegroundService(intent)
        isPlaying = !isPlaying

        return isPlaying
    }

    fun playNext() {
        playMusic(getNext(currentId)!!.id)
    }

    fun playPrevious() {
        playMusic(getPrevious(currentId)!!.id)
    }


    /**
     * 通知栏UI及事件设置的方法
     */
    fun startForeground(service: Service, song: Song, startPlayed: Boolean) {
        val channelId =
            createNotificationChannel("music_service", "Music Background Service")

        //普通notification用到的视图
        val normalView =
            RemoteViews(MusicApplication.instance().packageName, R.layout.song_normal_notification)
        //显示bigView的notification用到的视图
        val bigView =
            RemoteViews(MusicApplication.instance().packageName, R.layout.song_big_notification)


        /**设置普通视图start*/
        normalView.setTextViewText(R.id.music_name, song.name)

        var bitmap = LocalMusicUtils.loadingCover(song.path)
        if (bitmap != null) {
            bitmap = ImageUtils.toRoundCorner(bitmap, 200)
            normalView.setImageViewBitmap(R.id.music_img, bitmap)
        } else {
            normalView.setImageViewResource(R.id.music_img, R.mipmap.ic_logo)
        }



        normalView.setTextViewText(R.id.music_singer_name, song.singer)
//        normalView.setImageViewResource(com.huawei.glass.R.id.music_previous, com.huawei.glass.R.mipmap.player_ic_previous_blue)
        normalView.setImageViewResource(
            R.id.music_pause,
            if (startPlayed) R.mipmap.player_ic_pause_blue else R.mipmap.player_ic_play_blue
        )
//        normalView.setImageViewResource(com.huawei.glass.R.id.music_next, com.huawei.glass.R.mipmap.player_ic_next_blue)
//        normalView.setImageViewResource(com.huawei.glass.R.id.music_next, com.huawei.glass.R.mipmap.player_ic_next_blue)


        val openAppIntent = Intent(MusicApplication.instance(), SongActivity::class.java)
        openAppIntent.putExtra(
            PlayService.SONG_ACTION_TYPE_KEY,
            PlayService.SONG_ACTION_TYPE_PREVIOUS
        )
        //打开activity时用PendingIntent.getActivity, 启动service时用getService,发送广播时使用getBroadcast
        val openAppPendingIntent = PendingIntent.getActivity(
            MusicApplication.instance(),
            80,//requestCode标识pendingintent，设置多个时注意设置不同，否则多个view会执行同一个pendingintent
            openAppIntent,
            PendingIntent.FLAG_IMMUTABLE
        )
        normalView.setOnClickPendingIntent(R.id.music_img, openAppPendingIntent)


        val previousIntent = Intent(MusicApplication.instance(), PlayService::class.java)
        previousIntent.putExtra(
            PlayService.SONG_ACTION_TYPE_KEY,
            PlayService.SONG_ACTION_TYPE_PREVIOUS
        )
        //打开activity时用PendingIntent.getActivity, 启动service时用getService,发送广播时使用getBroadcast
        val previousPendingIntent = PendingIntent.getService(
            MusicApplication.instance(),
            PlayService.SONG_ACTION_TYPE_PREVIOUS,//requestCode标识pendingintent，设置多个时注意设置不同，否则多个view会执行同一个pendingintent
            previousIntent,
            PendingIntent.FLAG_IMMUTABLE
        )
        normalView.setOnClickPendingIntent(R.id.music_previous, previousPendingIntent)


        val pauseIntent = Intent(MusicApplication.instance(), PlayService::class.java)
        pauseIntent.putExtra(
            PlayService.SONG_ACTION_TYPE_KEY,
            if (startPlayed) PlayService.SONG_ACTION_TYPE_PAUSE else PlayService.SONG_ACTION_TYPE_CONTINUE
        )
        //打开activity时用PendingIntent.getActivity, 启动service时用getService,发送广播时使用getBroadcast
        val pausePendingIntent = PendingIntent.getService(
            MusicApplication.instance(), PlayService.SONG_ACTION_TYPE_PAUSE,
            pauseIntent,
            (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ) PendingIntent.FLAG_MUTABLE else 0) or PendingIntent.FLAG_UPDATE_CURRENT
        )
        normalView.setOnClickPendingIntent(R.id.music_pause, pausePendingIntent)


        val nextIntent = Intent(MusicApplication.instance(), PlayService::class.java)
        nextIntent.putExtra(PlayService.SONG_ACTION_TYPE_KEY, PlayService.SONG_ACTION_TYPE_NEXT)
        //打开activity时用PendingIntent.getActivity, 启动service时用getService,发送广播时使用getBroadcast
        val nextPendingIntent = PendingIntent.getService(
            MusicApplication.instance(), PlayService.SONG_ACTION_TYPE_NEXT,
            nextIntent, PendingIntent.FLAG_IMMUTABLE
        )
        normalView.setOnClickPendingIntent(R.id.music_next, nextPendingIntent)


        /**设置普通视图end*/

        /**设置大视图start*/
        bigView.setTextViewText(R.id.music_name, song.name)
        bigView.setTextViewText(R.id.music_singer_name, song.singer)
        bigView.setImageViewResource(
            R.id.music_big_notify_pause,
            if (startPlayed) R.mipmap.player_ic_pause_blue else R.mipmap.player_ic_play_blue
        )

        val loopImg: Int = SongUtils.getLoopImg(PlayService.loopType)

        bigView.setImageViewResource(R.id.music_big_notify_loop_type, loopImg)

        if (bitmap != null) {
            bigView.setImageViewBitmap(R.id.music_img, bitmap)
        } else {
            bigView.setImageViewResource(R.id.music_img, R.mipmap.ic_logo)
        }


        val openAppIntentBig = Intent(MusicApplication.instance(), SongActivity::class.java)
        openAppIntent.putExtra(
            PlayService.SONG_ACTION_TYPE_KEY,
            PlayService.SONG_ACTION_TYPE_PREVIOUS
        )
        //打开activity时用PendingIntent.getActivity, 启动service时用getService,发送广播时使用getBroadcast
        val openAppPendingIntentBig = PendingIntent.getActivity(
            MusicApplication.instance(),
            81,//requestCode标识pendingintent，设置多个时注意设置不同，否则多个view会执行同一个pendingintent
            openAppIntentBig,
            PendingIntent.FLAG_IMMUTABLE
        )
        bigView.setOnClickPendingIntent(R.id.music_img, openAppPendingIntentBig)


        val previousIntentBig = Intent(MusicApplication.instance(), PlayService::class.java)
        previousIntentBig.putExtra(
            PlayService.SONG_ACTION_TYPE_KEY,
            PlayService.SONG_ACTION_TYPE_BIG_NOTIFY_PREVIOUS
        )
        //打开activity时用PendingIntent.getActivity, 启动service时用getService,发送广播时使用getBroadcast
        val previousPendingIntentBig = PendingIntent.getService(
            MusicApplication.instance(),
            PlayService.SONG_ACTION_TYPE_BIG_NOTIFY_PREVIOUS,//requestCode标识pendingintent，设置多个时注意设置不同，否则多个view会执行同一个pendingintent
            previousIntentBig,
            PendingIntent.FLAG_IMMUTABLE
        )
        bigView.setOnClickPendingIntent(R.id.music_big_notify_previous, previousPendingIntentBig)


        val pauseIntentBig = Intent(MusicApplication.instance(), PlayService::class.java)
        pauseIntentBig.putExtra(
            PlayService.SONG_ACTION_TYPE_KEY,
            if (startPlayed) PlayService.SONG_ACTION_TYPE_BIG_NOTIFY_PAUSE else PlayService.SONG_ACTION_TYPE_BIG_NOTIFY_CONTINUE
        )
        //打开activity时用PendingIntent.getActivity, 启动service时用getService,发送广播时使用getBroadcast
        val pausePendingIntentBig = PendingIntent.getService(
            MusicApplication.instance(), PlayService.SONG_ACTION_TYPE_BIG_NOTIFY_PAUSE,
            pauseIntentBig, PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
        bigView.setOnClickPendingIntent(R.id.music_big_notify_pause, pausePendingIntentBig)


        val nextIntentBig = Intent(MusicApplication.instance(), PlayService::class.java)
        nextIntentBig.putExtra(
            PlayService.SONG_ACTION_TYPE_KEY,
            PlayService.SONG_ACTION_TYPE_BIG_NOTIFY_NEXT
        )
        //打开activity时用PendingIntent.getActivity, 启动service时用getService,发送广播时使用getBroadcast
        val nextPendingIntentBig = PendingIntent.getService(
            MusicApplication.instance(), PlayService.SONG_ACTION_TYPE_BIG_NOTIFY_NEXT,
            nextIntentBig, PendingIntent.FLAG_IMMUTABLE
        )
        bigView.setOnClickPendingIntent(R.id.music_big_notify_next, nextPendingIntentBig)


        //bigview下有looptype设置
        val loopIntent = Intent(MusicApplication.instance(), PlayService::class.java)
        loopIntent.putExtra(
            PlayService.SONG_ACTION_TYPE_KEY,
            SongUtils.getNextLoopType(PlayService.loopType)
        )
        //打开activity时用PendingIntent.getActivity, 启动service时用getService,发送广播时使用getBroadcast
        val loopPendingIntent = PendingIntent.getService(
            MusicApplication.instance(), PlayService.SONG_ACTION_TYPE_LOOP_ALL,
            loopIntent,
            (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ) PendingIntent.FLAG_MUTABLE else 0) or PendingIntent.FLAG_UPDATE_CURRENT
        )
        bigView.setOnClickPendingIntent(R.id.music_big_notify_loop_type, loopPendingIntent)
        /**大视图设置end*/


        val notificationBuilder = NotificationCompat.Builder(service, channelId)
        val notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.mipmap.ic_logo)
            .setPriority(PRIORITY_MAX)
            .setCategory(Notification.CATEGORY_SERVICE)
            .setContentTitle(song.name)
            .setContentText(song.singer)
            .setWhen(System.currentTimeMillis())
            .setShowWhen(true)

            .setSmallIcon(R.mipmap.ic_logo)
            .setTicker("开始播放啦~~")
            .setOngoing(true)
            .setContent(normalView)//设置普通notification视图
            .setCustomContentView(normalView)//设置普通notification视图
            .setCustomBigContentView(bigView)//设置显示bigView的notification视图
            .setPriority(PRIORITY_MAX)//设置最大优先级
            .setStyle(NotificationCompat.BigPictureStyle())
//            .setContentIntent(getDefaultIntent(Notification.FLAG_ONGOING_EVENT))


            .build()
        service.startForeground(1, notification)
    }
}